package com.zheng.mall.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.util.StringUtil;
import com.zheng.mall.dao.*;
import com.zheng.mall.dto.PmsProductParam;
import com.zheng.mall.dto.PmsProductQueryParam;
import com.zheng.mall.dto.PmsProductResult;
import com.zheng.mall.mapper.*;
import com.zheng.mall.model.*;
import com.zheng.mall.service.PmsProductService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 商品管理Service
 * @author zheng
 */
@Service
public class PmsProductServiceImpl implements PmsProductService {
    private static final Logger LOGGER = LoggerFactory.getLogger(PmsProductServiceImpl.class);
    @Autowired
    private PmsProductMapper productMapper;
    @Autowired
    private PmsMemberPriceDao memberPriceDao;
    @Autowired
    private PmsMemberPriceMapper memberPriceMapper;
    @Autowired
    private PmsProductLadderDao productLadderDao;
    @Autowired
    private PmsProductLadderMapper productLadderMapper;
    @Autowired
    private PmsProductFullReductionDao productFullReductionDao;
    @Autowired
    private PmsProductFullReductionMapper productFullReductionMapper;
    @Autowired
    private PmsSkuStockDao skuStockDao;
    @Autowired
    private PmsSkuStockMapper skuStockMapper;
    @Autowired
    private PmsProductAttributeValueDao productAttributeValueDao;
    @Autowired
    private PmsProductAttributeValueMapper productAttributeValueMapper;
    @Autowired
    private CmsSubjectProductRelationDao subjectProductRelationDao;
    @Autowired
    private CmsSubjectProductRelationMapper subjectProductRelationMapper;
    @Autowired
    private CmsPrefrenceAreaProductRelationDao prefrenceAreaProductRelationDao;
    @Autowired
    private CmsPrefrenceAreaProductRelationMapper prefrenceAreaProductRelationMapper;
    @Autowired
    private PmsProductDao productDao;
    @Autowired
    private PmsProductVertifyRecordDao productVertifyRecordDao;

    /**
     * 创建商品
     *
     * @param productParam
     */
    @Override
    public int create(PmsProductParam productParam) {
        int count;
        PmsProduct product = productParam;
        product.setId(null);
        productMapper.insertSelective(product);
        Long productId = product.getId();
        //根据促销类设置价格
        //会员价格
        relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), productId);
        //阶梯价格
        relateAndInsertList(productLadderDao, productParam.getProductLadderList(),productId);
        //减满价格
        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), productId);
        //处理sku的编码
        handleSkuStockCode(productParam.getSkuStockList(), productId);
        //添加sku库存
        relateAndInsertList(skuStockDao, productParam.getSkuStockList(), productId);
        //添加商品参数，添加自定义商品规格
        relateAndInsertList(productAttributeValueDao, productParam.getSubjectProductRelationList(), productId);
        //关联专题
        relateAndInsertList(subjectProductRelationDao, productParam.getSubjectProductRelationList(), productId);
        //关联优选
        relateAndInsertList(prefrenceAreaProductRelationDao, productParam.getPrefrenceAreaProductRelationList(), productId);
        count = 1;
        return count;
    }

    /**
     * 根据商品编号获取更新信息
     *
     * @param id
     */
    @Override
    public PmsProductResult getUpdateInfo(Long id) {
        return productDao.getUpdateInfo(id);
    }

    /**
     * 更新商品
     *
     * @param id
     * @param productParam
     */
    @Override
    public int update(Long id, PmsProductParam productParam) {
        int count;
        PmsProduct product = productParam;
        product.setId(id);
        productMapper.updateByPrimaryKeySelective(product);
        //会员价格
        PmsMemberPriceExample priceExample = new PmsMemberPriceExample();
        priceExample.createCriteria().andProductIdEqualTo(id);
        memberPriceMapper.deleteByExample(priceExample);
        relateAndInsertList(memberPriceDao, productParam.getMemberPriceList(), id);
        //阶梯价格
        PmsProductLadderExample ladderExample = new PmsProductLadderExample();
        ladderExample.createCriteria().andProductIdEqualTo(id);
        productLadderMapper.deleteByExample(ladderExample);
        relateAndInsertList(productLadderDao, productParam.getProductLadderList(),id);
        //减满价格
        PmsProductFullReductionExample reductionExample = new PmsProductFullReductionExample();
        reductionExample.createCriteria().andProductIdEqualTo(id);
        productFullReductionMapper.deleteByExample(reductionExample);
        relateAndInsertList(productFullReductionDao, productParam.getProductFullReductionList(), id);
        //处理sku的编码
        handleUpdateStock(id, productParam);
        //添加sku库存
        PmsSkuStockExample skuStockExample = new PmsSkuStockExample();
        skuStockExample.createCriteria().andProductIdEqualTo(id);
        skuStockMapper.deleteByExample(skuStockExample);
        relateAndInsertList(skuStockDao, productParam.getSkuStockList(), id);
        //添加商品参数，添加自定义商品规格
        PmsProductAttributeValueExample valueExample = new PmsProductAttributeValueExample();
        valueExample.createCriteria().andProductIdEqualTo(id);
        productAttributeValueMapper.deleteByExample(valueExample);
        relateAndInsertList(productAttributeValueDao, productParam.getSubjectProductRelationList(), id);
        //关联专题
        CmsSubjectProductRelationExample subjectRelationExample = new CmsSubjectProductRelationExample();
        subjectRelationExample.createCriteria().andProductIdEqualTo(id);
        subjectProductRelationMapper.deleteByExample(subjectRelationExample);
        relateAndInsertList(subjectProductRelationDao, productParam.getSubjectProductRelationList(), id);
        //关联优选
        CmsPrefrenceAreaProductRelationExample preferenceRelationExample = new CmsPrefrenceAreaProductRelationExample();
        preferenceRelationExample.createCriteria().andProductIdEqualTo(id);
        prefrenceAreaProductRelationMapper.deleteByExample(preferenceRelationExample);
        relateAndInsertList(prefrenceAreaProductRelationDao, productParam.getPrefrenceAreaProductRelationList(), id);
        count = 1;
        return count;
    }

    /**
     * 分页查询商品
     *
     * @param productQueryParam
     * @param pageSize
     * @param pageNum
     */
    @Override
    public List<PmsProduct> list(PmsProductQueryParam productQueryParam, Integer pageSize, Integer pageNum) {
        PageHelper.startPage(pageNum, pageSize);
        PmsProductExample productExample = new PmsProductExample();
        PmsProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andDeleteStatusEqualTo(0);
        if (productQueryParam.getPublishStatus() != null) {
            criteria.andPublishStatusEqualTo(productQueryParam.getPublishStatus());
        }
        if (productQueryParam.getVerifyStatus() != null) {
            criteria.andVerifyStatusEqualTo(productQueryParam.getVerifyStatus());
        }
        if (!StringUtils.isEmpty(productQueryParam.getKeyword())) {
            criteria.andKeywordsLike("%" + productQueryParam.getKeyword() + "%");
        }
        if (!StringUtils.isEmpty(productQueryParam.getProductSn())) {
            criteria.andProductSnEqualTo(productQueryParam.getProductSn());
        }
        if (productQueryParam.getBrandId() != null) {
            criteria.andBrandIdEqualTo(productQueryParam.getBrandId());
        }
        if (productQueryParam.getProductCategoryId() != null) {
            criteria.andProductCategoryIdEqualTo(productQueryParam.getProductCategoryId());
        }
        return productMapper.selectByExample(productExample);
    }

    /**
     * 批量修改审核状态
     *
     * @param ids          产品id
     * @param verifyStatus 审核状态
     * @param detail       审核详情
     */
    @Override
    public int updateVerifyStatus(List<Long> ids, Integer verifyStatus, String detail) {
        PmsProduct product = new PmsProduct();
        product.setVerifyStatus(verifyStatus);
        PmsProductExample productExample  = new PmsProductExample();
        productExample.createCriteria().andIdIn(ids);
        List<PmsProductVertifyRecord> vertifyRecordList = new ArrayList<>();
        int count = productMapper.updateByExampleSelective(product, productExample);
        //修改完成后插入审核记录
        for (Long id : ids) {
            PmsProductVertifyRecord vertifyRecord = new PmsProductVertifyRecord();
            vertifyRecord.setId(id);
            vertifyRecord.setCreateTime(new Date());
            vertifyRecord.setDetail(detail);
            vertifyRecord.setVertifyMan("admin");
            vertifyRecordList.add(vertifyRecord);
        }
        productVertifyRecordDao.insertList(vertifyRecordList);
        return count;
    }

    /**
     * 批量修改商品上架状态
     *
     * @param ids
     * @param publishStatus
     */
    @Override
    public int updatePublishStatus(List<Long> ids, Integer publishStatus) {
        PmsProduct product = new PmsProduct();
        product.setPublishStatus(publishStatus);
        PmsProductExample productExample = new PmsProductExample();
        productExample.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(product, productExample);
    }

    /**
     * 批量修改商品推荐状态
     *
     * @param ids
     * @param recommendStatus
     */
    @Override
    public int updateRecommendStatus(List<Long> ids, Integer recommendStatus) {
        PmsProduct product = new PmsProduct();
        product.setRecommandStatus(recommendStatus);
        PmsProductExample productExample = new PmsProductExample();
        productExample.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(product, productExample);
    }

    /**
     * 批量修改新品状态
     *
     * @param ids
     * @param newStatus
     */
    @Override
    public int updateNewStatus(List<Long> ids, Integer newStatus) {
        PmsProduct product = new PmsProduct();
        product.setNewStatus(newStatus);
        PmsProductExample productExample = new PmsProductExample();
        productExample.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(product, productExample);
    }

    /**
     * 批量删除商品
     *
     * @param ids
     * @param deleteStatus
     */
    @Override
    public int updateDeleteStatus(List<Long> ids, Integer deleteStatus) {
        PmsProduct product = new PmsProduct();
        product.setDeleteStatus(deleteStatus);
        PmsProductExample productExample = new PmsProductExample();
        productExample.createCriteria().andIdIn(ids);
        return productMapper.updateByExampleSelective(product, productExample);
    }

    /**
     * 根据商品名称或者货号模糊查询
     *
     * @param keyword
     */
    @Override
    public List<PmsProduct> list(String keyword) {
        PmsProductExample productExample = new PmsProductExample();
        PmsProductExample.Criteria criteria = productExample.createCriteria();
        criteria.andDeleteStatusEqualTo(0);
        if (!StringUtils.isEmpty(keyword)) {
            criteria.andNameLike("%" + keyword +"%");
            productExample.or().andDeleteStatusEqualTo(0).andProductSnNotLike("%" + keyword +"%");
        }
        return productMapper.selectByExample(productExample);
    }

    /**
     * 建立和插入关系表操作
     *
     * @param dao       可以操作的dao
     * @param dataList  要插入的数据
     * @param productId 建立关系的id
     */
    private void relateAndInsertList (Object dao, List dataList, Long productId) {
        try {
            if (CollectionUtils.isEmpty(dataList)){
                return;
            }
            for (Object item: dataList) {
                Method setId = item.getClass().getMethod("setId", Long.class);
                setId.invoke(item, (Long)null);
                Method setProductId = item.getClass().getMethod("setProductId", Long.class);
                setProductId.invoke(item, productId);
            }
            Method insertList = dao.getClass().getMethod("insertList", List.class);
            insertList.invoke(dao, dataList);
        } catch (Exception e) {
            LOGGER.warn("创建产品出错:{}", e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
    }

    /**
     * 添加sku库存信息
     *
     * @param skuStockList
     * @param productId
     */
    private void handleSkuStockCode (List<PmsSkuStock> skuStockList, Long productId) {
        if (CollectionUtils.isEmpty(skuStockList)){
            return;
        }
        for (int i = 0; i < skuStockList.size(); i++) {
            PmsSkuStock skuStock = skuStockList.get(i);
            if(StringUtil.isEmpty(skuStock.getSkuCode())) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
                StringBuilder sb = new StringBuilder();
                sb.append(sdf.format(new Date()));
                //四位商品id
                sb.append(String.format("%04d", productId));
                //三位索引id
                sb.append(String.format("%03d", i+1));
                skuStock.setSkuCode(sb.toString());
            }
        }
    }

    /**
     * 更新库存信息
     *
     * @param id
     * @param productParam
     */
    private void handleUpdateStock (Long id, PmsProductParam productParam) {
        //当前sku信息
        List<PmsSkuStock> currSkuList = productParam.getSkuStockList();
        //当前没有sku直接删除
        if (CollectionUtils.isEmpty(currSkuList)) {
            PmsSkuStockExample skuStockExample = new PmsSkuStockExample();
            skuStockExample.createCriteria().andProductIdEqualTo(id);
            skuStockMapper.deleteByExample(skuStockExample);
            return;
        }
        //获取初始sku信息
        PmsSkuStockExample skuStockExample = new PmsSkuStockExample();
        skuStockExample.createCriteria().andProductIdEqualTo(id);
        List<PmsSkuStock> selectSkuList = skuStockMapper.selectByExample(skuStockExample);
        //获取新增sku信息
        List<PmsSkuStock> insertSkuList  = currSkuList.stream().filter(item -> item.getId() == null).collect(Collectors.toList());
        //获取需要更新的sku信息
        List<PmsSkuStock> updateSkuList = currSkuList.stream().filter(item -> item.getId() != null).collect(Collectors.toList());
        List<Long> updateSkuIds = updateSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
        //获取需要删除的sku信息
        List<PmsSkuStock> deleteSkuList = selectSkuList.stream().filter(item -> !updateSkuIds.contains(item.getId())).collect(Collectors.toList());
        //新增Sku
        if (!CollectionUtils.isEmpty(insertSkuList)) {
            relateAndInsertList(skuStockDao, insertSkuList, id);
        }
        //更新Sku
        if (!CollectionUtils.isEmpty(updateSkuList)) {
            for (PmsSkuStock pmsSkuStock : updateSkuList) {
                skuStockMapper.updateByPrimaryKeySelective(pmsSkuStock);
            }
        }
        //删除Sku
        if (!CollectionUtils.isEmpty(deleteSkuList)) {
            List<Long> deleteIdList = deleteSkuList.stream().map(PmsSkuStock::getId).collect(Collectors.toList());
            PmsSkuStockExample deleteExample = new PmsSkuStockExample();
            deleteExample.createCriteria().andIdIn(deleteIdList);
            skuStockMapper.deleteByExample(deleteExample);
        }
    }
}
